package at.jku.pervasive.simulator;

import java.io.IOException;
import java.util.Random;

import at.jku.pervasive.Helper;
import at.jku.pervasive.Position;

public class RandomUbisenseServerSimulator extends UbisenseServerSimulator
{

	private Random random;

	private double width;
	private double length;
	private double height;
	private final String[] ids;
	private Position[] latestPosition;

	public RandomUbisenseServerSimulator(int port, String... ids)
	{
		super(port);

		random = new Random();

		latestPosition = new Position[ids.length];
		for (int i = 0; i < ids.length; i++)
		{
			latestPosition[i] = new Position(ids[i], 0.0, 0.0, 1.0, Helper.now());
		}

		width = 10.0;
		height = 2.8;
		length = 15.0;

		this.ids = ids;
	}

	public RandomUbisenseServerSimulator(int port) throws IOException
	{
		this(port, "1");
	}

	public void setDimensions(double width, double length, double height)
	{
		this.width = width;
		this.length = length;
		this.height = height;
	}

	@Override
	protected long getWaitingTime()
	{
		// wait between 30 and 529 ms
		// return (long) (random.nextDouble() * 150) + 30;
		return 200;
	}

	@Override
	protected Position getNextPosition()
	{
		int index = (int) ((random.nextDouble() * ids.length) % ids.length);
		String id = ids[index];
		
		Position currentPosition = latestPosition[index];
		
		double x = currentPosition.getX();
		double y = currentPosition.getY();
		double z = currentPosition.getZ();

		x += (random.nextDouble() - 0.5) * 2.0;
		y += (random.nextDouble() - 0.5) * 2.0;
		z += (random.nextDouble() - 0.5) * 0.15;

		latestPosition[index] = new Position(id, Math.min(Math.abs(x), width), Math.min(Math.abs(y), length), Math.min(Math
				.abs(z), height), Helper.now());
		return currentPosition;
	}

}
